package com.codemonkey.lq.common.util;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;

/** 
 * From http://stamen.iteye.com/blog/2030552 <br>
 * 
 * 用处:
 * <pre>
 * 	 类包冲突（典型症状是java.lang.ClassNotFoundException或Method不兼容等异常）
 *   使用此类查找类的真正出处
 * </pre>
 *  
 * @author : chenxh 
 * @date: 13-10-31 
 */
public class ClassLocationUtils {

	/** 
	 * 获取类所有的路径(查看Class所来源的JAR包) <br>
	 * @param cls 
	 * @return 
	 */
	public static String where(final Class cls) {
		if (cls == null)
			throw new IllegalArgumentException("null input: cls");
		URL result = null;
		final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
		final ProtectionDomain pd = cls.getProtectionDomain();
		if (pd != null) {
			final CodeSource cs = pd.getCodeSource();
			if (cs != null)
				result = cs.getLocation();
			if (result != null) {
				if ("file".equals(result.getProtocol())) {
					try {
						if (result.toExternalForm().endsWith(".jar")
								|| result.toExternalForm().endsWith(".zip"))
							result = new URL("jar:".concat(result.toExternalForm()).concat("!/")
									.concat(clsAsResource));
						else if (new File(result.getFile()).isDirectory())
							result = new URL(result, clsAsResource);
					} catch (MalformedURLException ignore) {
					}
				}
			}
		}
		if (result == null) {
			final ClassLoader clsLoader = cls.getClassLoader();
			result = clsLoader != null ? clsLoader.getResource(clsAsResource) : ClassLoader
					.getSystemResource(clsAsResource);
		}
		return result.toString();
	}

}